<template>
  <div class="auth-page">
    <div class="container page">
      <div class="row">

        <div class="col-md-6 offset-md-3 col-xs-12">
          <h1 class="text-xs-center">{{isLogin?'Sign in':'Sign up'}}</h1>
          <p class="text-xs-center">
            <nuxt-link v-if="isLogin" to="/register">Need an account?</nuxt-link>
            <nuxt-link v-else to="/login">Have an account?</nuxt-link>
          </p>

          <ul class="error-messages">
            <template v-for="(messages,field) in errors">
              <li v-for="(message,index) in messages" :key="index">{{field}}{{message}}</li>
            </template>
          </ul>

          <form @submit.prevent="onSubmit">
            <fieldset class="form-group" v-if="isLogin">
              <label>
                <input class="form-control form-control-lg" v-model="user.name" type="text"
                       placeholder="Your Name" required>
              </label>
            </fieldset>
            <fieldset class="form-group">
              <label>
                <input class="form-control form-control-lg" v-model="user.email" type="Email"
                       placeholder="Email" required>
              </label>
            </fieldset>
            <fieldset class="form-group">
              <label>
                <input class="form-control form-control-lg" v-model="user.password" type="password"
                       placeholder="Password" required>
              </label>
            </fieldset>
            <button class="btn btn-lg btn-primary pull-xs-right">
              {{isLogin?'Sign in':'Sign up'}}
            </button>
          </form>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/user';

export default {
  name: 'loginIndex',
  computed: {
    isLogin() {
      return this.$route.name === 'login';
    }
  },
  data() {
    return {
      user: {
        email: '',
        password: ''
      },
      errors: {}
    };
  },
  methods: {
    async onSubmit() {
      try {
        const { data } = await login({
          user: this.user
        });
        console.log(data);
        this.$router.push('/');
      } catch (e) {
        console.dir(e);
        console.log(e.response.data.errors);
        console.log(e.response.status);
        this.errors = e.response.data.errors;
      }
    },
  }
};
</script>

<style scoped>

</style>
